// abnormallyReport.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    faultItems: [
      { name: '路灯不亮', value: '路灯不亮' },
      { name: '灯杆损坏倾斜', value: '灯杆损坏倾斜'},
      { name: '线缆外露损坏', value: '线缆外露损坏' },
      { name: '灯杆门缺损', value: '灯杆门缺损' },
      { name: '附近成片熄灯', value: '附近成片熄灯' },
      { name: '灯具破损', value: '灯具破损' }
    ],
    gzList: ['路灯不亮', '灯杆损坏倾斜', '线缆外露损坏', '灯杆门缺损', '附近成片熄灯', '其他故障'],
    faultDescription: "",
    canRemark:false,
    str1:['a'],
    str2: 'a',
    facilitiesNo: '',//设施编号
    streetLampType: '',//路灯类型
    address: '',//地址
    jwdInfo: '',//经纬度
    // powerUnit: '',//权属单位
    name: '',
    phone: '',
    deptid: 0,//部门id
    loading: false,
    userInfo: {},
    exlist: [],
    radioVal: '',
    exobj: {},
    moreChflag: true,
    id: '',
    type: 0,
    tittleInfo:'',
    mapshow:true,
    longitude: 113.324520,
    latitude: 23.099994,
    remark:'',
    streetLampId:'',
    hasScene:false,
    imgshow:[],
    imgUrl:[],
    deptPhone:"86881114",
    detail:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = options.scene?decodeURIComponent(options.scene) : '';
    this.setData({
      navHeight:app.globalData.navHeight
    })
    
    if (scene != 'undefined' && scene){
      console.log(scene)
      that.setData({ id: scene, hasScene:true,});
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getUserInfo();
    var that = this;
    var scene = that.data.id;
    if (scene != '') {
      //查询故障信息
      that.searchEX(scene);
    } else {
      //需要登录系统账号信息
      // that.checkLogin();
      // wx.setNavigationBarTitle({
      //   title: wx.getStorageSync('deptName')
      // })
    }
  },
  onShareAppMessage: function () {

  },
  getUserInfo: function () {
    var that = this
    wx.getUserInfo({
      lang: 'zh_CN',
      success: function (res) {
        
      },
      fail: function (res) {
        wx.showModal({
          title: '需要您授权才能正常显示',
          content: '请点击“去授权”并点击授权按钮，即可正常使用',
          confirmText: '去授权',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              // wx.openSetting({
              //   success: function (re) {
              //     if (!re.authSetting["scope.userInfo"] || !re.authSetting["scope.userLocation"]) {
              //       var isset = that.data.isSetUserInfo
              //       if(!isset){
              //         that.getUserInfo()
              //       }
              //     }else{
              //       that.setData({ isSetUserInfo : true})
              //     }
              //   }
              // })
              console.log("用户点击确定")
              wx.navigateTo({
                url: '../authorize/authorize',
              })
            }
          }
        })
      }
    })
  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName')
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  //当获取焦点时触发
  focusFun: function(e){
    var that = this;
    var param = e.target.dataset.param;
    that.searchEXlist();
    var val = 0;
    var tittle = '终端编号选择';
    if (param==1){
      val = 1;
      tittle = '终端编号选择';
    } else if (param == 3){
      val = 3;
      tittle = '地址选择';
    } else if (param == 4) {
      val = 4;
      tittle = '经纬度选择';
    }
    that.setData({type:val,tittleInfo:tittle});
  },
  //根据id查询
  searchEX: function(id){
    var that = this;
    var header = { 'content-type': 'application/x-www-form-urlencoded' };
    var param = {id: id};
    wx.request({
      url: app.url + '/web/streetLamp/getById.htm',
      data: app.ecbEncrypto(param),
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest);
        if (rest.isSuccess == 0) {
          var entity = rest.result;
          that.setData({
            facilitiesNo: entity.meterAddr,//设施编号
            streetLampType: entity.streetLampType,//路灯类型
            address: entity.address,//地址
            jwdInfo: entity.lngLat,//经纬度
            // powerUnit: entity.powerUnit,//权属单位
            deptid: entity.deptid,
            deptPhone: entity.deptPhone,
            streetLampId: id,
            detail:entity
          });
          // wx.setNavigationBarTitle({
          //   title: entity.powerUnit
          // })
          console.log(entity)
        }
      }
    })
  },
  //查询集合获取终端编号
  searchEXlist: function () {
    var that = this;
    var header = { 'content-type': 'application/x-www-form-urlencoded' };
    let params = {
      deptId: wx.getStorageSync('deptId'), 
    }
    console.log(params)
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr)
    wx.request({
      url: app.url + '/web/exceptionReport/select.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest);
        if (rest.isSuccess == 0) {
          that.setData({
            exlist: rest.result,
            moreChflag: false
          });
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  //为空判断
  getValue:function(e){
    var that = this;
    var param = e.target.dataset.param;
    var val = e.detail.value;
    if(param == 1){
      that.setData({ facilitiesNo: val.trim()});
    }else if(param == 2){
      that.setData({ streetLampType: val.trim() });
    }else if(param == 3){
      that.setData({ address: val.trim() });
    } else if (param == 4){
      that.setData({ jwdInfo: val.trim() });
    } 
    // else if (param == 5){
    //   that.setData({ powerUnit: val.trim() });
    // } 
    else if (param == 6) {
      that.setData({ name: val.trim() });
    } else if (param == 7) {
      that.setData({ phone: val.trim() });
    } else if (param == 8) {
      that.setData({ remark: val.trim() });
    }
  },
  checkboxChange:function(e){
    var cboxs = e.detail.value;
    var faultItems = this.data.faultItems;
    var val = cboxs.toString();
    faultItems.forEach((item,index)=>{
      item.checked = cboxs.indexOf(item.value) > -1
    })
    var canRemark = cboxs.indexOf('其他故障') > -1;
    if (!canRemark){
      this.setData({remark:''})
    }
      this.setData({ faultDescription: val, faultItems: faultItems, canRemark: canRemark});
  },
  exsubmit: function(){
    
    var that = this;
    var faultDescription = that.data.faultDescription;
    var facilitiesNo = that.data.facilitiesNo;
    var streetLampType = that.data.streetLampType;
    var address = that.data.address;
    var jwdInfo = that.data.jwdInfo;
    // var powerUnit = that.data.powerUnit;
    var name = that.data.name;
    var phone = that.data.phone;
    var remark = that.data.remark;
    // if (facilitiesNo == '') {
    //   wx.showToast({
    //     title: '设施编号不能为空',
    //     image: '../../images/error.png',
    //     duration: 2000,
    //     mask: true
    //   })
    //   return false;
    // }
    if (streetLampType == '') {
      wx.showToast({
        title: '路灯类型不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (address == '') {
      wx.showToast({
        title: '地址不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (jwdInfo == '') {
      wx.showToast({
        title: '经纬度不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    // if (powerUnit == '') {
    //   wx.showToast({
    //     title: '单位不能为空',
    //     image: '../../images/error.png',
    //     duration: 2000,
    //     mask: true
    //   })
    //   return false;
    // }
    if (faultDescription.length==0 && !remark) {
      wx.showToast({
        title: '请选择故障描述',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (name == '') {
      wx.showToast({
        title: '请输入您的名字',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    var preg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    var greg = /^(0\d{2,3}-\d{7,8})$/;
    if (phone == '') {
      wx.showToast({
        title: '请输入您的联系电话',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    } 
    // if((!preg.test(phone) || phone.length!=11) && !greg.test(phone) && phone != ''){
    //   wx.showToast({
    //     title: '电话格式不正确',
    //     image: '../../images/error.png',
    //     duration: 2000,
    //     mask: true
    //   })
    //   return false;
    // }
    if(phone.length < 8){
      wx.showToast({
        title: '电话格式不正确',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    var params= {
      faultDescription:faultDescription,
      facilitiesNo:facilitiesNo,
      streetLampType:streetLampType,
      address:address,
      jwdInfo:jwdInfo,
      // powerUnit:powerUnit,
      name:name,
      phone:phone,
      deptid: that.data.deptid,
      remark: remark,
      imgUrl: that.data.imgUrl.toString(),
      streetLampId: that.data.streetLampId,
      type:2
    }
    console.log(params)
    that.setData({loading:true});
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/exceptionReport/add.htm',
      data: encodingStr,
      method: 'POST',
      type: 'json',
      success: function(res){
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        that.setData({ loading: false });
        if (rest.isSuccess == 0) {
          // wx.showModal({
          //   title: '',
          //   content:"您的问题已上报至花都路灯管理所，我们会尽快安排处理，谢谢！",
          //   showCancel:false,
          //   success: function () {
          //     if (that.data.hasScene){
          //       wx.reLaunch({ url: '../about/about?id=' + that.data.streetLampId })
          //     }else{
          //       wx.switchTab({
          //         url: '../control/controlBooth',
          //       })
          //     }
          //   }
          // })
          wx.showToast({
            title: '上报成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(function () {
            //要延时执行的代码
            if (that.data.hasScene){
              wx.reLaunch({ url: '../about/about?id=' + that.data.streetLampId })
            }else{
              wx.switchTab({
                url: '../control/controlBooth',
              })
            }     
          }, 1000) //延迟时间
        }else{
          that.setData({ loading: false });
          wx.showToast({
            title: '故障上报失败',
            image: '../../images/error.png',
            duration: 2000
          })
        }
      }
    })
  },
  clickFun: function(e){
    var id = e.currentTarget.dataset.id;
    var ob = e.currentTarget.dataset.ob;
    this.setData({ radioVal: id ,exobj: ob});
  },
  sureButton: function () {
    var that = this;
    that.setData({ 
      moreChflag: true, 
      facilitiesNo: that.data.exobj.meterAddr,
      address: that.data.exobj.address,
      jwdInfo: that.data.exobj.lngLat,
      deptid: that.data.exobj.deptid,
      streetLampType: that.data.exobj.streetLampType,//路灯类型
      // powerUnit: that.data.exobj.powerUnit,//权属单位
      streetLampId: that.data.exobj.id,
      deptPhone: that.data.exobj.deptPhone
    });
  },
  hideMoreCh: function () {
    this.setData({ moreChflag: true })
  },
  mapshow: function(){
    this.setData({ mapshow: !this.data.mapshow })
  },
  openMap: function (event) {
    var that=this
    if (this.data.jwdInfo!=""){
      that.setData({
        longitude: parseFloat(this.data.jwdInfo.split(',')[0]),
        latitude: parseFloat(this.data.jwdInfo.split(',')[1])
      })
      
      wx.navigateTo({
        url: '../control/query?latitude=' + that.data.latitude + '&longitude=' + that.data.longitude,
      })
    }   
  },
  chooseImage(e) {
    var that = this;
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'Accept-Encoding': 'gzip, deflate',
      'Accept-Language': 'zh-CN,zh; q=0.8',
      'Accept': '*/*',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Content-Length': '64',
      'Pragma': 'no-cache',
    };
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;

        tempFilePaths.forEach((item,index)=>{
          if(index < 5){
            wx.uploadFile({
              url: app.url + '/api/account/wxupload.htm',
              filePath: item,
              name: 'file',
              formData: {
                'user': 'test'
              },
              success(res) {
                console.log(res.data)
                var imgUrlList = that.data.imgUrl
                imgUrlList = imgUrlList.concat([res.data])
    
                var imgshowList = that.data.imgshow;
                imgshowList = imgshowList.concat([item])
  
                that.setData({
                  imgUrl: imgUrlList,
                  imgshow: imgshowList,
                })
              }
            })
          }
          
        })

        console.log(tempFilePaths);

        

      }
    })
  },
  callPhone(){
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.deptPhone,
    })
  },
  deleteImg(e){
    var index = e.currentTarget.dataset.index;
    var imgUrlList = this.data.imgUrl
    var imgshowList = this.data.imgshow;
    imgUrlList.splice(index,1)
    imgshowList.splice(index,1)    
    this.setData({
      imgUrl:imgUrlList,
      imgshow:imgshowList,
    })
  }
})